import { TOKEN, USER_INFO } from '@/utils/constants';
import { setItem, getItem, removeAllItem } from '@/utils/storage';


export const useUserInfoStore = defineStore('user', {
  state: () => {
    return {
      token: getItem(TOKEN) || '',
      userInfo: getItem(USER_INFO),
    };
  },

  getters: {
    token: (state) => {
      return state.token;
    },

    openid: (state) => {
      const userInfo = getInfo(state);
      if (userInfo && userInfo.openId) {
        return userInfo.openId;
      }
      return '';
    },

    unionId: (state) => {
      const userInfo = getInfo(state);
      if (userInfo && userInfo.unionId) {
        return userInfo.unionId;
      }
      return '';
    },

    // 用户id
    userId: (state) => {
      const userInfo = getInfo(state);
      if (userInfo && userInfo.userId) {
        return userInfo.userId;
      }
      return '';
    },

    //  客户id
    wxUserId: (state) => {
      const userInfo = getInfo(state);
      if (userInfo && userInfo.wxUserId) {
        return userInfo.wxUserId;
      }
      return '';
    },

    nickName: (state) => {
      const userInfo = getInfo(state);
      if (userInfo && userInfo.nickName) {
        return userInfo.nickName;
      }
      return '';
    },

    phone: (state) => {
      const userInfo = getInfo(state);
      if (userInfo && userInfo.phone) {
        return userInfo.phone;
      }
      return '';
    },

    // 手机号
    phoneStar(state) {
      const userInfo = getInfo(state);
      if (userInfo && userInfo.phone) {
        const phone = userInfo.phone;
        return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      }
      return '';
    },

    avatarUrl: (state) => {
      const userInfo = getInfo(state);
      if (userInfo && userInfo.avatarUrl) {
        return userInfo.avatarUrl;
      }
      return '';
    },

    loginInfo: (state) => {
      const userInfo = getInfo(state);
      return userInfo;
    }
  },

  actions: {
    wxLogin(info) {
      this.userInfo = info;
      setItem(TOKEN, info.token);
      setItem(USER_INFO, info);
    },
    logout() {
      removeAllItem();
      this.userInfo = null;
    }
  },
});

const getInfo = (state) => {
  let userInfo = state.userInfo;
  if (!userInfo) {
    userInfo = getItem(USER_INFO);
  }
  return userInfo;
};

